import { All, Body, Controller, Inject, Param, Req } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { Request } from 'express';

@Controller('api/:service')
export class GatewayController {
  private clients: Map<string, ClientProxy> = new Map();

  constructor(
    @Inject('SERVICES_CONFIG') private servicesConfig: { name: string; options: any }[],
    @Inject() private clientProxies: ClientProxy[],
  ) {
    // 将所有客户端代理存储在Map中以便快速查找
    this.clientProxies.forEach(client => {
      const name = Reflect.getMetadata('name', client);
      if (name) {
        this.clients.set(name, client);
      }
    });
  }

  @All(':path(*)')
  processRequest(
    @Param('service') service: string,
    @Param('path') path: string,
    @Body() body: any,
    @Req() req: Request,
  ): Observable<any> {
    const client = this.clients.get(service);
    if (!client) {
      throw new Error(`服务 ${service} 未找到`);
    }

    return client.send(
      { cmd: path || 'default', method: req.method },
      { body, query: req.query, params: req.params }
    );
  }
}